package com.examlpe.lotterysystem.common.interceptor;

import com.examlpe.lotterysystem.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 预处理
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String token = request.getHeader("user_token");
        log.info("获取token:{}",token);
        log.info("获取路径:{}",request.getRequestURI());
        //令牌解析
        Claims claims = JWTUtil.parseJWT(token);
        if(null == claims) {
            log.error("解析jwt令牌失败！");
            response.setStatus(401);
            return false;
        }

        log.info("解析JWT令牌成功!放行！");
        return true;
    }
}
